import React, {FC, useContext, useMemo, useRef, useState} from 'react';
import "./index.less";
import WordCloud from "react-d3-cloud";
import {useRequest, useSize} from "ahooks";
import * as API from "@/services";
import {queryFrontMyUserTag} from "@/services";
import {HxConfigContext} from "@/layouts/HxConfigContext";
import {correspVal} from "@/utils/biz";
import {FormattedMessage} from "umi";
import queryString from "query-string";

interface UserProfileAnalysisProps {
}


type Word = {
  text: string;
  value: number;
}

/**
 * 用户画像分析 页面
 */
const UserProfileAnalysis: FC<UserProfileAnalysisProps> = (props) => {

  const {isZhCN} = useContext(HxConfigContext);

  const queryFrontMyUserTagReq = useRequest(() => API.queryFrontMyUserTag(), {
    manual: false,
  })

  const myUserTag = queryFrontMyUserTagReq.data?.data;

  const words: Word[] = useMemo(() => {
    let ret: Word[] = [];
    if (myUserTag) {
      const userTabWeights = correspVal(isZhCN, myUserTag.contentTagSysCnDto, myUserTag.contentTagSysEnDto)
      ret = userTabWeights?.map((tag: API.UserTag_Weight) => {
        return {
          text: tag.contentTagName,
          value: tag.weight,
        }
      }) || []
    }
    return ret;
  }, [isZhCN, myUserTag]);


  // 字体大小映射函数 - 核心配置
  const fontSizeMapper = (word: Word) => {
    // 根据权重值动态计算字体大小
    // 可以使用线性映射、对数映射或自定义公式
    return Math.sqrt(word.value) * 10; // 平方根映射，避免过大值
  };

  // 自定义颜色映射函数
  const wordColorMapper = (word: Word) => {
    // 根据权重值动态调整颜色
    const hue = 220 - word.value; // 从蓝色过渡到紫色
    return `hsl(${hue}, 70%, 50%)`;
  };

  // 自定义方向映射函数
  const wordRotateMapper = (word: Word) => {
    return (word.value % 90) - 45;
  }

  // 鼠标悬停效果
  const [hoveredWord, setHoveredWord] = useState(null);

  const worldcloudWrapRef = useRef<HTMLDivElement>(null);
  const worldcloudWrapSize = useSize(worldcloudWrapRef);
  const worldcloudWidth = worldcloudWrapSize?.width;


  const WordCloudComp = useMemo(() => {
    return (
      <WordCloud
        width={worldcloudWidth || 442}
        height={263}
        data={words}
        fontSize={fontSizeMapper}
        fill={wordColorMapper}
        rotate={wordRotateMapper}
        padding={2}
        onWordClick={(event, d) => {
          const searchStr = queryString.stringify({
            dsl: `ID=("${d.text.trim()}")`
          })
          window.open(`/search-adv/article?${searchStr}`)
        }}
        onWordMouseOver={(event, d) => {
          //console.log(`onWordMouseOver: ${d.text}`);
        }}
        onWordMouseOut={(event, d) => {
          //console.log(`onWordMouseOut: ${d.text}`);
        }}
      />
    )
  }, [worldcloudWidth, words]);


  return (
    <div className={"user-profile-analysis-container"}>
      <div className={"user-profile-analysis-tip"}><FormattedMessage id="mine.UserProfileAnalysisTip"/></div>
      <div className={"user-profile-analysis-content"} ref={worldcloudWrapRef}>
        {WordCloudComp}
      </div>
    </div>
  );
};

export default UserProfileAnalysis;
